from machine import Pin, UART, Timer
from machine import Timer
import time
import bluetooth
from car import CAR
# from machine import Pin,Timer
from neopixel import NeoPixel

#定义红、绿、蓝三种颜色
RED=(25,0,0)
GREEN=(0,25,0)
LEFT=(0,25,25)
RIGHT= (25,0,25)

BLACK = (0,0,0)
global num
num = 8

#22引脚连接灯带，灯珠数量30
pin = Pin(5, Pin.OUT)
np = NeoPixel(pin, 25)

#设置灯珠颜色，本实验供30个灯珠
def Color_buf(color):
    for i in range(25):
        np[i]=color

def ws(color):
    for i in range(0,10):
        np[num + i] = color
        np.write()
        np[num - i] = color
        np.write()
        np[num + i + 1] = color
        np.write()
        np[num - i - 1] = color
        np.write()
        np[num + i + 2] = color
        np.write()
        np[num - i - 2] = color
        np.write()
        np[num + i + 3] = color
        np.write()
        np[num - i - 3] = color
        np.write()        
        np[num + i] = BLACK
        np.write()        
        np[num - i] = BLACK
        np.write()
        time.sleep(0.2)

buf = bytes(0)
BLE_MSG = ""
# uart = UART(1, baudrate=115200, tx=17, rx=16)

class ESP32_BLE():
    def __init__(self, name):
        self.led = Pin(2, Pin.OUT)
        self.timer1 = Timer(0)
        self.name = name
        self.ble = bluetooth.BLE()
        self.ble.active(True)
        self.ble.config(gap_name=name)
        self.disconnected()
        self.ble.irq(self.ble_irq)
        self.register()
        self.advertiser()

    def connected(self):
        self.led.value(1)
        self.timer1.deinit()

    def disconnected(self):        
        self.timer1.init(period=100, mode=Timer.PERIODIC, callback=lambda t: self.led.value(not self.led.value()))

    def ble_irq(self, event, data):
        global BLE_MSG
        if event == 1: #_IRQ_CENTRAL_CONNECT 手机链接了此设备
            self.connected()
        elif event == 2: #_IRQ_CENTRAL_DISCONNECT 手机断开此设备
            self.advertiser()
            self.disconnected()
        elif event == 3: #_IRQ_GATTS_WRITE 手机发送了数据 
            buffer = self.ble.gatts_read(self.rx)
            BLE_MSG = buffer.decode('UTF-8').strip()
            
    def register(self):        
        service_uuid = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'
        reader_uuid = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E'
        sender_uuid = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E'

        services = (
            (
                bluetooth.UUID(service_uuid), 
                (
                    (bluetooth.UUID(sender_uuid), bluetooth.FLAG_NOTIFY), 
                    (bluetooth.UUID(reader_uuid), bluetooth.FLAG_WRITE),
                )
            ), 
        )

        ((self.tx, self.rx,), ) = self.ble.gatts_register_services(services)

    def send(self, data):
        self.ble.gatts_notify(0, self.tx, data + '\n')

    def advertiser(self):
        name = bytes(self.name, 'UTF-8')
        adv_data = bytearray('\x02\x01\x02') + bytearray((len(name) + 1, 0x09)) + name
        self.ble.gap_advertise(100, adv_data)
        print(adv_data)
        print("\r\n")

if __name__ == "__main__":
    ble = ESP32_BLE("ESP32BLE")

    # 控制蓝色led
    led = Pin(2, Pin.OUT)
    
    global speed
    speed = 200
    Car = CAR()
    Car.setspeed(speed)
    
    
    
    while True:
        led.value(not led.value)
             
        if BLE_MSG == 'read_LED':
            print(BLE_MSG)
            BLE_MSG = ""
            print('LED is ON.' if led.value() else 'LED is OFF')
            ble.send('LED is ON.' if led.value() else 'LED is OFF')
        elif BLE_MSG:
            print("接收到的信息：>>%s<<" % BLE_MSG)
            if BLE_MSG == ("!B11:" or "!B10;") :  # 按下app上数字1
#                 Car.up_left()
                ws(LEFT)
            elif BLE_MSG == ("!B219" or "!B20:") :  # 按下app上数字2
#                 Car.up_right()
                ws(RIGHT)
            elif BLE_MSG == ("!B309" or "!B318") :  # 按下app上数字3
                Car.Counterclockwise()
                speed = speed + 10
                Car.setspeed(speed)
                ble.send('占空比为：'+ str(Car.duty       )+'(最大为1023)')
                
            elif BLE_MSG == ("!B417" or "!B408") :  # 按下app上数字4
                Car.clockwise()
                speed = speed - 10
                Car.setspeed(speed)
                ble.send('占空比为：'+ str(Car.duty       )+'(最大为1023)')
            elif BLE_MSG == ("!B516" or "!B507") :  # 按下app上up键
                Car.up()
                ws(GREEN)
            elif BLE_MSG == ("!B705" or "!B714") :  # 按下app上left键
                Car.left()
                ws(LEFT)
            elif BLE_MSG == ("!B813" or "!B804") :  # 按下app上right键
                Car.right()
                ws(RIGHT)
            elif BLE_MSG == ("!B615" or "!B606") :  # 按下app上down键
                Car.stop()
                ws(RED)
            BLE_MSG = ""

        time.sleep_ms(10)


